(function(window) {
	var o = {};

	o.plusReady = function(callback) {
		/*mui.plusReady(function() {
			callback();
		});*/
		if(window.plus) {
			setTimeout(function() { //解决callback与plusready事件的执行时机问题(典型案例:showWaiting,closeWaiting)
				callback();
			}, 0);
		} else {
			document.addEventListener("plusready", function() {
				callback();
			}, false);
		}
		return this;
	};
	o.webTest = function(callback) {
		setTimeout(function() {
			if(!window.plus) {
				callback();
			}
		}, 600);
	};

	o.addCls = function(el, cls) {

		if('classList' in el) {
			el.classList.a.formatterdd(cls);
		} else {
			var preCls = el.className;
			var newCls = preCls + ' ' + cls;
			el.className = newCls;
		}
		return el;
	};
	o.removeCls = function(el, cls) {

		if('classList' in el) {
			el.classList.remove(cls);
		} else {
			var preCls = el.className;
			var newCls = preCls.replace(cls, '');
			el.className = newCls;
		}
		return el;
	};

	o.showLoading = function(text, options) {
		if(!window.plus) return;
		var defaultOptions = {
			background: 'rgba(120,120,120,0.8)',
			padding: '15px'
		}
		if(!text) {
			text = "加载中...";
		}
		options = options || {};
		options = o.extend(defaultOptions, options);
		plus.nativeUI.showWaiting(text, options);
		
	}

	o.closeLoading = function(text, options) {
		if(!window.plus) return;
		plus.nativeUI.closeWaiting();
	}

	o.showToast = function(text, options) {
		if(!window.plus) return;
		options = options || {};
		plus.nativeUI.toast(text, options);
	}

	o.getStorage = function() {
		if(window.plus) {
			return plus.storage;
		}
		return window.localStorage;
	};
	o.logout = function() {
		o.getStorage().removeItem("user_obj");
		o.getStorage().removeItem("__password__");
	};
	o.setUser = function(val) {
		var roleSet = {};
		for(var i in val.roles) {
			roleSet[val.roles[i]] = i;
		}
		val.roleSet = roleSet;

		val.modules = {};
		val.modules.main = './html/main.html';
		o.getStorage().setItem("user_obj", JSON.stringify(val));
		return true;
	};

	/**
     * return user object
     * {
			"orgId": 1,
			"id": 1,
			"createTime": "2017-02-27 16:05:02",
			"roles": [1],
	*		 roleSet:{'INTERNAL_JS001':1}
			"realName": "超级管理员",
			"orgName": "甘家口",
			"password": "admin",
			"lastModifyTime": "2017-02-27 16:05:06",
			"loginName": "admin"
		}

     */
	o.getUser = function() {
		var strUserObj = o.getStorage().getItem("user_obj");
		if(strUserObj) {
			return JSON.parse(strUserObj);
		} else {
			return null;
		}
		//return {id:'1',loginName:'zdd',realName:'张达达',roleSet:{'INTERNAL_JS001':1},orgId:'402891e9550493db015504ce78d80002',orgName:'一组',modules:{main:'./html/main.html'}};
	};

	o.isAdmin = function() {
		if(!o.getUser()) {
			return false;
		}
		var roles = o.getUser().roleSet;
		return "1" in roles || "2" in roles;
	};

	o.isLogin = function() {
		var isLogin = false;
		var userObj = o.getUser();
		if(userObj && userObj.id && userObj.loginName) {
			isLogin = true;
		}
		return isLogin;
	};
	o.extend = function() {
		var obj = {};
		for(var i in arguments) {
			for(var k in arguments[i]) {
				if(arguments[i].hasOwnProperty(k)) {
					obj[k] = arguments[i][k];
				}
			}
		}
		return obj;
	}
	o.log = function(msg) {
		console.log(msg);
	}

	o.distinct = function(a, b) {
		var radALat = rad(a.latitude);
		var radBLat = rad(b.latitude);
		var x = radALat - radBLat;
		var y = rad(a.longitude) - rad(b.longitude);
		var dst = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(x / 2), 2) + Math.cos(radALat) * Math.cos(radBLat) * Math.pow(Math.sin(y / 2), 2)));
		dst = dst * 6378137;
		return Math.round(dst * 1000) / 1000;
	}

	function rad(a) {
		return a * Math.PI / 180;
	}

	/**
	 * 
	 * $app.ajax({
			url: $url,
			data: $data
		}, function(ret, err) {
		});
	 * @param {Object} options {url,data,type,dataType,timeout}
	 * @param {Object} callback function(ret, err)
	 */
	o.ajax = function(options, callback) {
		var defaultOptions = {
			dataType: 'json', //服务器返回json格式数据
			type: 'get', //HTTP请求类型
			crossDomain: true, //强制使用5+跨域
			timeout: 10000, //超时时间设置为10秒
			success: function(data) {
				o.log("响应数据：" + JSON.stringify(data).substring(0, 200));
				if(callback) {
					callback(data);
				}
			},
			error: function(xhr, type, errorThrown) {
				o.log("错误信息：" + JSON.stringify(type));
				if(callback) {
					callback(null, { statusCode: 500, code: 0, msg: type });
				}
			}
		};
		var realOptions = o.extend(defaultOptions, options);

		realOptions.data = o.extend({}, realOptions.data);
		if(o.getUser()) {
			realOptions.data.__loginUserID__ = o.getUser().id;
			realOptions.data.__loginUserType__ = o.getUser().type;
		}

		o.log("发生请求(jquery)：" + JSON.stringify(realOptions));
		if(window.plus) {
			mui.ajax(options.url, realOptions);
		}else{
			jqueryAjax(options.url, realOptions);
		}
	};
	
	function jqueryAjax(url, options){
		$.ajax({
			type: options.type,
			url: url,
			data: options.data,
			dataType: options.dataType,
			success: function(data, status, xhr){
				options.success(data);
			},
			error: function(xhr, type){
				options.error(xhr, type);
			}
		});
	}
	
	o.queryFromTextData = function(url, fields, callback){
		o.ajax({
			type:'get',
			dataType:'text',
			url: url,
			data:{time:new Date().getTime()}
		}, function(ret, err){
			if(ret){
				var dataList = ret.trim().split('\n');
				
				var objList = [];
				for(var i in dataList){
					var rowStr = dataList[i];
					if(rowStr){
						var row = rowStr.split(',');
						var obj = {};
						for(var fIdx in fields){
							obj[fields[fIdx]] = row[fIdx];
						}
						objList.push(obj);
					}
				}
				ret = objList;
			}
			callback(objList, err);
		});
	}
	/**
	 * 打开新窗口
	 * @param {Object} options {id:'',url:'',...}
	 */
	o.openWindow = function(options) {
		var defaultOptions = {
			show: {
				aniShow: 'pop-in'
			},
			extras: {

			}
		};

		var realOptions = o.extend(defaultOptions, options);
		var url = options.url;
		if(!url) {
			return;
		}
		var params = {};
		if(url && url.indexOf('?') > -1) {
			var paramString = url.split('?')[1];
			params = parseParam(paramString);
		}
		if(window.plus) {
			realOptions.url = url.split('?')[0];
		}
		realOptions.extrasget = realOptions.extras || {};
		realOptions.extras.params = realOptions.extras.params || {};
		realOptions.extras.params = o.extend(realOptions.extras.params, params);

		mui.openWindow(realOptions);
	};

	var parseParam = function(paramStr) {
		var params = {};
		var paramArr = paramStr.split('&');
		paramArr.forEach(function(item) {
			var pName = item.split('=')[0];
			var pValue = item.split('=')[1];
			params[pName] = pValue;
		});
		return params;
	}

	o.pullRefresh = function($scope, options) {
		var defaultOptions = options || {};
		if(!defaultOptions.container) {
			alert("没有指定容器");
		}
		var upOptions = {
			height: 50, //可选.默认50.触发上拉加载拖动距离
			auto: true, //可选,默认false.自动上拉加载一次
			contentrefresh: "正在加载...", //可选，正在加载状态时，上拉加载控件上显示的标题内容
			contentnomore: '没有更多数据了', //可选，请求完毕若没有更多数据时显示的提醒内容；
			callback: function() {

			} //必选，刷新函数，根据具体业务来编写，比如通过ajax从服务器获取新数据；
		}
		var pullRefreshOptions = {
			container: defaultOptions.container
		}
		mui.init({
			pullRefresh: {
				container: refreshContainer, //待刷新区域标识，querySelector能定位的css选择器均可，比如：id、.class等
				up: {

				}
			}
		});
	}

	o.getParams = function() {
		if(window.plus) {
			return plus.webview.currentWebview().params || {};
		} else {
			var searchStr = location.search;
			if(searchStr) {
				var paramStr = searchStr.substr(1, searchStr.length);
				return parseParam(paramStr);
			}
			return {};
		}
	};
	o.formatter = {
		text: function(val) {
			return val || '';
		},
		date: function(dateStr) {
			return dateStr ? dateStr.substring(0, 10) : '';
		}
	}
	o.dicData = {
		task: {
			status: function(val) {
				var text = ['待审核', '招标中', '选标中', '已中标', '已完成', '已评价', '任务取消', '任务超时关闭', '审核不通过'];
				return text[val - 1] || '';
			},
			volunteerType: function(val) {
				var text = ['实名认证志愿者', '同社区实名认证志愿者'];
				return text[val - 1] || '';
			}

		},
		bid: {
			status: function(val) {
				var text = ['未中标', '已中标', '已完成', '已评价', '', '', '', '', '已放弃'];
				return text[val - 1] || '';
			}
		}
	};

	o.choosePicture = function(callback) {
		var btnArray = [{
			title: "拍照"
		}, {
			title: "从相册选择"
		}];
		plus.nativeUI.actionSheet({
			title: "选择照片",
			cancel: "取消",
			buttons: btnArray
		}, function(e) {
			var index = e.index;
			if(index == 1) {
				var cmr = plus.camera.getCamera();
				cmr.captureImage(function(path) {					
					compressImage(path,path, callback);
					
				}, function(err) {});
			} else if(index == 2) {
				plus.gallery.pick(function(path) {
					var dst = "_doc/"+new Date().getTime()+".jpg";
					compressImage(path,dst, callback);
				}, function(err) {}, null);
			}
		});
	};

	function compressImage(src,dst, callback) {
		plus.zip.compressImage({
			src: src,
			overwrite: true,
			dst: dst,
			quality: 30
		}, function(event) {
			callback(event.target);
		}, function(err) {
			alert("选择失败");
		});
	}

	o.compressImage = compressImage;

	/**
	 * 文件上传
	 * @param {Object} options {url:'', file:''}
	 * @param {Object} callback: function(ret, err)
	 */
	o.upload = function(options, callback) {
		var task = plus.uploader.createUpload(options.url, { method: "POST", blocksize: 204800, priority: 100 },
			function(t, status) {
				// 上传完成
				if(status == 200) {
					callback(t.responseText, null);
				} else {
					callback(null, { status: status });
				}
			}
		);
		task.addFile(options.file, { key: "uploadfile" });
		task.start();
	};

	o.download = function(url, callback) {
		var dtask = plus.downloader.createDownload(url, {},
			function(d, status) {
				// 下载完成
				if(status == 200) {
					callback(d.filename, null);
				} else {
					callback(null, { status: status });
				}
			});
		//dtask.addEventListener( "statechanged", onStateChanged, false );
		dtask.start();
	};
	
	o.sendPhoneCode = function(){
		
	}

	/**
	 * $app.save({
			url: $config.url.im.message.send,
			entityData: message
		},function(ret,err){
			if(ret){
				if(ret.success){ //保存成功
					//dosomething
				}else{
					mui.alert(ret.errors.join(","),'提交失败'); 
				}
			}else{
				mui.alert(JSON.stringify(err),'系统异常'); 
			}
		});
	 * 保存
	 * @param {Object} options {url:'', entityData:{}, params:{}}
	 * @param {Object} callback: function(ret, err)
	 */
	o.save = function(options, callback) {
		var data = options.params || {};
		data.__form_data__ = JSON.stringify(options.entityData);
		o.ajax({
			url: options.url,
			type: 'post',
			data: data
		}, function(ret, err) {
			callback(ret, err);
		});
	};

	window.$app = o;
})(window);

(function($app) {
	/**
	 * 
	 * @param {Object} options 
	 * 		{
	 * 			url:数据请求url,
	 * 			params:数据请求参数,
	 * 			isPage:是否分页加载
	 * 			rows: 每次加载数据条数，默认 20
	 * 			showLoading:是否显示加载框
	 * 			showError:加载错误是否alert提示，默认false
	 * 			beforeLoadData: function(params) 开始加载数据事件
	 * 			onLoadData: function(ret, err) 数据加载完事件,
	 * 			$scope: angular $scope对象，配合angular实时刷新使用【可选】
	 * 		}
	 * Data{
	 * 		status:{
	 * 			loading:[boolean]:是否正在加载数据
	 * 			isMoreLoading:[boolean]:是否正在加载更多数据【分页查询（isPage=true）时有效】
	 * 			isLoadedAll: 是否已经加载完所有数据【分页查询（isPage=true）时有效】
	 * 			isError:[boolean]:是否报错
	 * 		}
	 * 		options:[object]:设置对象
	 * 		data:[object]:加载的数据
	 * }
	 * Function:
	 * 		loadData: params,
	 * 		loadMoreData: params
	 */
	var Data = function(options) {
		var defaultOptions = {
			$scope: { $apply: function() {}, showLoading: false, isPage: false, rows: 20 }
		}
		this.status = { loading: false, isLoadedAll: false, isError: false };
		this.options = $app.extend(defaultOptions, options);
		if(this.options.isPage) {
			this.options.params = this.options.params || {};
			this.options.params.rows = this.options.rows;
		}
		this.data = null;

		this._init();
	};

	Data.prototype = {
		_init: function() {
			//加载数据
			this.loadData();
		},
		loadData: function(params, isLoadMore, callback) {
			// 如果正在加载，则退出
			if(this.status.loading) {
				return;
			}
			if(isLoadMore && this.options.isPage) {
				if(this.status.isLoadedAll) {
					return;
				} else if(this.status.isMoreLoading) {
					return;
				} else {
					this.status.isMoreLoading = true;
				}
			}
			this.status.loading = true;
			setTimeout(function() {
				this.options.$scope.$apply();
			}.bind(this), 0);

			if(this.options.showLoading) {
				$app.showLoading();
			}

			this.options.params = $app.extend(this.options.params, params);
			if(this.options.isPage) {
				if(isLoadMore) {
					this.options.params.startIndex = (this.data || []).length;
				} else {
					this.options.params.startIndex = 0;
				}

			}
			if(this.options.beforeLoadData) {
				this.options.beforeLoadData.call(this, this.options.params);
			}

			$app.ajax({
				type: 'get',
				url: this.options.url,
				data: this.options.params
			}, function(data, err) {
				if(this.options.showLoading) {
					$app.closeLoading();
				}
				if(err) {
					if(!isLoadMore) {
						this.data = null;
					}
				} else {
					data = renderData(data, this.options.isPage);

					if(this.options.isPage) {
						this.status.isLoadedAll = data.length < this.options.rows;
					}
					if(isLoadMore) {
						this.data = this.data.concat(data);
					} else {
						this.data = data;
					}
				}
				this.status.loading = false;
				this.status.isMoreLoading = false;
				this.options.$scope.$apply();

				if(isLoadMore) {
					if(this.options.onLoadMoreData) {
						this.options.onLoadMoreData.call(this, data, err);
					}
				} else {
					if(this.options.onLoadData) {
						this.options.onLoadData.call(this, data, err);
					}
				}
				if(callback) {
					callback.call(this, data, err);
				}

				if(err && this.options.showError) {
					mui.alert(JSON.stringify(err), '系统异常');
				}
			}.bind(this));
		},
		loadMoreData: function(callback) {
			this.loadData(null, true, callback);
		},
		refreshData: function(callback) {
			this.loadData(null, false, callback);
		}
	};

	function renderData(data, isPage) {
		if(!data) {
			return [];
		}
		if(Array.isArray(data)) {
			return data;
		} else if(isPage) {
			if(data && Array.isArray(data.rows)) {
				return data.rows;
			} else {
				return [];
			}
		} else {
			return data;
		}
	}

	$app.Data = Data;
})(window.$app);

(function($app) {
	var $api = {
		css: function(el, css) {
			if(typeof css == 'string' && css.indexOf(':') > 0) {
				el.style && (el.style.cssText += ';' + css);
			}
		},
		cssVal: function(el, prop) {
			var computedStyle = window.getComputedStyle(el, null);
			return computedStyle.getPropertyValue(prop);
		},
		dom: function(selector) {
			return document.querySelector(selector);
		}
	}
	/**
	 * 新闻轮播组件
	 * @param {Object} $scope angular $scope对象
	 * @param {Object} sliderSelecter 轮播dom选择器
	 */
	var NewsSlider = function($scope, sliderSelecter) {
		this.firstNews = null;
		this.lastNews = null;
		this.news = new $app.Data({
			url: $config.url.article.news,
			$scope: $scope,
			onLoadData: function(ret, err) {
				if(ret) {

					var height = $api.cssVal($api.dom(sliderSelecter), 'height');
					$api.css($api.dom(sliderSelecter + " .mui-slider-group"), 'height:' + height);

					this.slider = mui(sliderSelecter);
					this.slider.slider({
						interval: 5000 //自动轮播周期，若为0则不自动播放，默认为0；
					});
				} else {
					//$app.alert(JSON.stringify(err));
				}
			}
		});
		this.firstNews = function() {
			if(this.news.data && this.news.data.length > 0) {
				return this.news.data[0];
			}
			return null;
		};
		this.firstNews = function() {
			if(this.news.data && this.news.data.length > 0) {
				return this.news.data[0];
			}
			return null;
		};
	};

	$app.NewsSlider = NewsSlider;
	window.$api = $api;
})(window.$app);

(function($app) {
	if(!window.mui) {
		return;
	}
	mui('body').on('tap', '.app-link', function(e) {
		e.stopPropagation();

		var id = this.getAttribute("data-wid");
		var url = this.getAttribute('href');
		if(!id) {
			id = url;
		}
		console.log(url);
		$app.openWindow({
			id: id,
			url: url
		});
	});
	mui('body').on('tap', '.app-logout', function(e) {
		e.stopPropagation();

		$app.logout();
		if(window.plus) {
			var wvs = plus.webview.all();
			for(var i = 1; i < wvs.length; i++) {
				plus.webview.close(wvs[i]);
			}
		} else {
			mui.back();
		}

	});

})(window.$app);

// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
// 例子： 
// (new Date()).format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
// (new Date()).format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
Date.prototype.format = function(fmt) { //author: meizz 
	var o = {
		"M+": this.getMonth() + 1, //月份 
		"d+": this.getDate(), //日 
		"h+": this.getHours(), //小时 
		"m+": this.getMinutes(), //分 
		"s+": this.getSeconds(), //秒 
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度 
		"S": this.getMilliseconds() //毫秒 
	};
	if(/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for(var k in o)
		if(new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
};

////// pullRefresh
/*
 * mui.init({
		pullRefresh: $app.buildPullRefresh({
			container:'#container',
			getPageData:function(){
				return module.$scope.pageData;
			}
		})
	});
	//刷新上拉刷新功能
	function refreshPullup(isLoadedAll){
		$app.refreshPullup('#container', isLoadedAll);
	}
 */
(function($app) {
	/**
	 * 
	 * @param {Object} options {
	 * 		container: 待刷新区域标识，querySelector能定位的css选择器均可，比如：#id、.class等,
	 * 		getPageData[function]:获取pageData对象的方法
	 * }
	 */
	function buildPullRefresh(options) {
		return {
			container: options.container, //待刷新区域标识，querySelector能定位的css选择器均可，比如：id、.class等
			up: {
				height: 80,
				contentrefresh: "正在加载...",
				contentnomore: '已全部加载',
				callback: function() {
					console.log('pull up.....');
					options.getPageData().loadMoreData(function() {
						mui(options.container).pullRefresh().endPullupToRefresh(this.status.isLoadedAll);
					});
				}
			},
			down: {
				contentdown: "下拉可以刷新", //可选，在下拉可刷新状态时，下拉刷新控件上显示的标题内容
				contentover: "释放立即刷新", //可选，在释放可刷新状态时，下拉刷新控件上显示的标题内容
				contentrefresh: "正在刷新...", //可选，正在刷新状态时，下拉刷新控件上显示的标题内容
				callback: function() {
					console.log('pull down.....');
					options.getPageData().refreshData(function() {
						mui(options.container).pullRefresh().endPulldownToRefresh();
					});
				} //必选，刷新函数，根据具体业务来编写，比如通过ajax从服务器获取新数据；
			}
		}
	}
	/**
	 * 	container: 待刷新区域标识，querySelector能定位的css选择器均可，比如：#id、.class等,
	 */
	function refreshPullup(container, isLoadedAll) {
		mui(container).pullRefresh().scrollTo(0, 0, 100)
		//mui(container).pullRefresh().refresh(true);
		mui(container).pullRefresh().enablePullupToRefresh();
		mui(container).pullRefresh().endPullupToRefresh(isLoadedAll);
	}

	$app.buildPullRefresh = buildPullRefresh;
	$app.refreshPullup = refreshPullup;

})(window.$app);